package com.mindcraft.shop.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mindcraft.base.model.MindCraftResult;
import com.mindcraft.base.utils.CommonConst;
import com.mindcraft.base.utils.RedisConst;
import com.mindcraft.shop.client.UserClient;
import com.mindcraft.shop.mapper.CommentMapper;
import com.mindcraft.shop.mapper.CommunityImageMapper;
import com.mindcraft.shop.mapper.CommunityMapper;
import com.mindcraft.shop.mapper.LikeMapper;
import com.mindcraft.shop.po.*;
import com.mindcraft.shop.service.CommunityService;
import com.mindcraft.shop.vo.CommentVo;
import com.mindcraft.shop.vo.CommunityVo;
import com.mindcraft.shop.vo.RecordInfoQueryVo;
import com.mindcraft.user.po.McUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommunityServiceImpl extends ServiceImpl<CommunityMapper, Community> implements CommunityService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserClient userClient;

    @Autowired
    private CommunityImageMapper communityImageMapper;

    @Autowired
    private CommunityMapper communityMapper;


    @Override
    public MindCraftResult<Page> listRecord(RecordInfoQueryVo recordInfoVo) {

        //以下根据sortid进行分页后
        LambdaQueryChainWrapper<Community> lambdaQuery = lambdaQuery();

        lambdaQuery.eq(recordInfoVo.getCategoryId() != null, Community::getCategoryId, recordInfoVo.getCategoryId());

        lambdaQuery.orderByDesc(Community::getCreateTime);

        lambdaQuery.page(recordInfoVo);

        List<Community> records = recordInfoVo.getRecords();

        //处理数据，给record加上其他数据

        List<CommunityVo> communityVoList = new ArrayList<>();
        for (Community community : records) {
            CommunityVo communityVo = this.buildCommunityVo(community);

            communityVoList.add(communityVo);
        }

        recordInfoVo.setRecords(communityVoList);

        return MindCraftResult.success(recordInfoVo);
    }


    @Autowired
    private LikeMapper likeMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public MindCraftResult like(Like like) {

        //先向redis中写数据，最后想办法同步

        if (redisTemplate.hasKey(RedisConst.LIKE + like.getUserId()) && redisTemplate.opsForValue().get(RedisConst.LIKE + like.getUserId()).equals(like.getCommentId())) {
            return MindCraftResult.success("已经点赞过了");
        }


        //判断是否已经点赞
        LambdaQueryWrapper<Like> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Like::getUserId, like.getUserId()).eq(Like::getCommentId, like.getCommentId());
        Like like1 = likeMapper.selectOne(wrapper);
        if (like1 == null) {
            //表示用户未点赞
            commentMapper.updateLikeCountById(like.getCommentId());
            //保存入缓存
            redisTemplate.opsForValue().set(RedisConst.LIKE + like.getUserId(), like.getCommentId(), CommonConst.SAVE_EXPIRE, TimeUnit.SECONDS);

            //TODO 以后进行异步操作
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            like.setId(uuid);
            likeMapper.insert(like);
            return MindCraftResult.success();
        } else {
            return MindCraftResult.success("已经点赞过了");
        }


    }

    @Override
    public MindCraftResult sendComment(CommentVo commentVo) {


        //传入userid和commentID

        //根据userId和community_id找到评论
        //需要更新comments表，更新community表评论数量
        CommunityComment communityComment = new CommunityComment();


        communityComment.setParentCommentId(commentVo.getParentCommentId());

        String parentUserId = commentVo.getParentUserId();
        communityComment.setParentUserId(parentUserId);


        //如果是评论的评论，前端应该传入floorcommentid
        if (commentVo.getFloorCommentId() != null) {

            communityComment.setFloorCommentId(commentVo.getFloorCommentId());
        } else {
            communityComment.setFloorCommentId(commentVo.getParentCommentId());
        }


        communityComment.setCommunityId(commentVo.getCommunityId());
        communityComment.setUserId(commentVo.getUserId());
        communityComment.setCommentContent(commentVo.getCommentContent());

        commentMapper.insert(communityComment);


        //对community数据中commentCount进行+1
        Community community = new Community();

        UpdateWrapper<Community> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", commentVo.getCommunityId())
                .setSql("comment_count = comment_count + 1");

        communityMapper.update(null, updateWrapper);


        return MindCraftResult.success(commentVo);
    }


    private CommunityVo buildCommunityVo(Community community) {
        CommunityVo communityVo = new CommunityVo();
        String userId = community.getUserId();

        //TODO 查询出粉丝数
        McUser user = userClient.getUser(userId);

        BeanUtils.copyProperties(community, communityVo);

        communityVo.setUsername(user.getUsername());
        communityVo.setAvartarUrl(user.getUserpic());
        communityVo.setCommentCount(commentMapper.selectCount(
                new LambdaQueryWrapper<CommunityComment>()
                        .eq(CommunityComment::getCommunityId, community.getId())));


        LambdaQueryWrapper<CommunityImage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CommunityImage::getCommunityId, communityVo.getId());
        List<CommunityImage> communityImages = communityImageMapper.selectList(wrapper);

        if (communityImages != null) {


            List<String> collect = communityImages.stream().map(communityImage -> {
                return communityImage.getImg1();
            }).collect(Collectors.toList());


            communityVo.setImgList(collect);
        }

        return communityVo;
    }
}
